<?php
//Theme interface class
class ThemexInterface {

	public static $pages;
	
	//Init module
	public static function init() {
	
		//add theme options page to menu
		add_action('admin_menu',array(__CLASS__,'addAdminPage'));
		
		
		if(isset($_GET['themex_uploader'])) {		
			//render thickbox uploader
			add_action('admin_init',array(__CLASS__,'renderTB'));
		}
		
	}
	
	public static function renderTB() {
		add_filter('media_upload_tabs', array(__CLASS__,'filterTBTabs'));
		add_filter('attachment_fields_to_edit', array(__CLASS__,'renderTBUploader'), 10, 2);	
	}
	
	
	//Filter uploader tabs
	public static function filterTBTabs($tabs) {
		unset($tabs['type_url'], $tabs['gallery']);
    	return $tabs;
	}
	
	
	//Render additional uploader options
	public static function renderTBUploader($form_fields, $post) {
		
		//save fields
		$filename=basename($post->guid);
		$attachment_id=$post->ID;
		$attachment['post_title']='';
		$attachment['url']=$form_fields['image_url']['value'];
		$attachment['post_excerpt']='';
		
		//unset default fields
		unset($form_fields);
		
		//delete button
		if (current_user_can('delete_post', $attachment_id)) {
			if ( !EMPTY_TRASH_DAYS ) {
				$delete_button="<a href='".wp_nonce_url( "post.php?action=delete&amp;post=$attachment_id", 'delete-attachment_'.$attachment_id )."' id='del[$attachment_id]' class='delete'>".__( 'Delete Permanently' , 'midway' ).'</a>';
			} elseif ( !MEDIA_TRASH ) {
				$delete_button="<a href='#' class='del-link' onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\">".__( 'Delete' , 'midway' )."</a>
				 <div id='del_attachment_$attachment_id' class='del-attachment' style='display:none;'>".sprintf( __( 'You are about to delete <strong>%s</strong>.' , 'midway' ), $filename )."
				 <a href='".wp_nonce_url( "post.php?action=delete&amp;post=$attachment_id", 'delete-attachment_'.$attachment_id )."' id='del[$attachment_id]' class='button'>".__( 'Continue' , 'midway' )."</a>
				 <a href='#' class='button' onclick=\"this.parentNode.style.display='none';return false;\">".__( 'Cancel' , 'midway' )."</a>
				 </div>";
			} else {
				$delete_button="<a href='".wp_nonce_url( "post.php?action=trash&amp;post=$attachment_id", 'trash-attachment_'.$attachment_id )."' id='del[$attachment_id]' class='delete'>".__( 'Move to Trash' , 'midway' )."</a>
				<a href='".wp_nonce_url( "post.php?action=untrash&amp;post=$attachment_id", 'untrash-attachment_'.$attachment_id )."' id='undo[$attachment_id]' class='undo hidden'>".__( 'Undo' , 'midway' )."</a>";
			}
		} else {
			$delete='';
		}
		
		//send to editor button
		$send_button="<input type='submit' class='button' name='send[$attachment_id]' value='".esc_attr__( 'Insert This Item' , 'midway' )."' />";
		$send_button.="<input type='radio' checked='checked' value='full' id='image-size-full-$attachment_id' name='attachments[$attachment_id][image-size]' style='display:none;' />";
		$send_button.="<input type='hidden' value='' name='attachments[$attachment_id][post_title]' id='attachments[$attachment_id][post_title]' />";
		$send_button.="<input type='hidden' value='$attachment[url]' class='themex_image_url' name='attachments[$attachment_id][url]' id='attachments[$attachment_id][url]' />";
		$send_button.="<input type='hidden' value='' name='attachments[$attachment_id][post_excerpt]' id='attachments[$attachment_id][post_excerpt]' />";
		$form_fields['buttons']=array( 'tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send_button $delete_button</td></tr>\n" );
		
		return $form_fields;
	}
	
	
	//Add theme admin page
	public static function addAdminPage() {
		
		//add page to menu
		add_submenu_page( 'themes.php', __('Theme Options','midway'), __('Theme Options','midway'), 'administrator', 'theme-options', array(__CLASS__,'renderPage') );
		
	}

	//Render theme options page
	public static function renderPage() {
	
		//include page layout
		include(THEMEX_PATH.'admin/layout.php');
		
	}
	
	//Render menu from page headings
	public static function renderMenu() {
		
		$out='<ul>';
		if(is_array(self::$pages)) {
		
			//menu item index
			$index=1;
		
			foreach(self::$pages as $page) {
				$out.='<li class="item_'.$index.'" id="'.preg_replace('/\s+/','',$page['name']).'">'.$page['name'].'</li>';
				$index++;
			}
		}
		$out.='</ul>';
		echo $out;
		
	}
	
	//Render admin pages
	public static function renderPages() {
	
		//layout flag for pages
		$first=true;
		
		//define output
		$out='';
	
		foreach(ThemexCore::$options as $option) {
			
			if($option['type']=='page') {
			
				//enclose previous page
				if($first) {
					$first=false;
				} else {
					$out.='</div>';
				}
				
				//add menu item to pages
				self::$pages[]=$option;
			}
			
			//render current option
			$out.=self::renderOption($option);		
			
		}
		
		//close last page
		$out.='</div>';
		
		echo $out;
		
	}
	
	//Render metaboxes
	public static function renderMetabox() {
	
		global $post;
		
		//generate nonce
		$out='<input type="hidden" name="themex_nonce" value="'.wp_create_nonce($post->ID).'" />'; 
		$out.='<table class="form-table themex_meta_table">';
		
		//search for current post metaboxes
		foreach(ThemexCore::$components['meta_boxes'] as $meta_box) {
			if($meta_box['page']==$post->post_type) {
				foreach($meta_box['options'] as $option) {	
					//option description
					if(!isset($option['desc'])) {
						$option['desc']='';
					}
					
					//add post type prefix to option
					$option['id']='_'.$post->post_type.'_'.$option['id'];
					
					//get default option value
					$option['default']=get_post_meta($post->ID,$option['id'],true);
					
					//option class
					$class=isset($option['attributes']['class'])?$option['attributes']['class']:'';
					
					//render option					
					$out.='<tr class="'.$class.'"><th style="width:25%"><label for="'.$option['id'].'"><strong>'.$option['name'].'</strong><span>'.$option['desc'].'</span></label></th><td>';
					
					//hide default option name
					unset($option['name']);
					
					//render option
					$out.=self::renderOption($option);
					
				}
			}
		}
		
		$out.='</table>';
		
		echo $out;
	}	
	
	//Render option control
	public static function renderOption($option) {
	
		//get posts instance
		global $post;
		
		//define output
		$out='';
	
		//option wrappers
		if($option['type']!='page') {

			//parent options
			$parent='';
			if(isset($option['parent']) && is_array($option['parent'])) {
				$parent=$option['parent']['0'].' hidden themex_child_'.$option['parent']['1'];
			}
			
			//visibility
			$hidden='';
			if(isset($option['hidden'])) {
				$hidden='hidden';
			}
			
			//set wrapper type
			if(isset(ThemexCore::$modules[$option['type']])) {
				$wrapper='themex_module';
			} else {
				$wrapper='themex_option';
			}
			
			//option start
			$out.='<div class="'.$wrapper.' '.$option['type'].' '.$parent.' '.$hidden.'">';
			
			//option name
			if(isset($option['name']) && $option['type']!='checkbox') {
				$out.='<h3>'.$option['name'].'</h3>';
			}
		}
		
		//get option description
		if(isset($option['description'])) {
			$out.='<div class="themex_tip">'.$option['description'].'</div>';
		}
		
		//get option attributes
		$attributes='';
		if(isset($option['attributes']) && is_array($option['attributes'])) {
			foreach($option['attributes'] as $attr_name=>$attr_value) {
				$attributes.=$attr_name.'="'.$attr_value.'" ';
			}
		}
		
		//get option class
		if(!isset($option['class'])) {
			$option['class']='';
		}
		
		//get option value		
		if(isset($option['id']) && ThemexCore::getOption($option['id'])) {
			$value=stripslashes(ThemexCore::getOption($option['id']));
		} else if(isset($post) && get_post_meta($post->ID,$post->post_type.'_'.$option['id'],true)!='') {
			$value=get_post_meta($post->ID,$post->post_type.'_'.$option['id'],true);
		} else if(isset($option['default'])) {
			$value=$option['default'];
		} else {
			$value='';
		}
		
		//add elements before
		if(isset($option['before'])) {
			$out=$option['before'].$out;
		}
	
		switch($option['type']) {
			//page wrapper
			case 'page':
				$out.='<div class="themex_page" id="'.preg_replace('/\s+/','',$option['name']).'_page"><h2>'.$option['name'].'</h2>';
			break;
			
			//default text field
			case 'text':
				$out.='<input type="text" id="'.$option['id'].'" name="'.$option['id'].'" value="'.$value.'" '.$attributes.' />';
			break;
			
			//text field with number validation
			case 'number':
				$out.='<input type="number" id="'.$option['id'].'" name="'.$option['id'].'" value="'.(int)$value.'" '.$attributes.' />';
			break;
			
			//text field with date validation
			case 'date':
				$out.='<input type="text" id="'.$option['id'].'" name="'.$option['id'].'" class="datepicker" value="'.$value.'" '.$attributes.' />';
			break;
			
			case 'hidden':
				$out.='<input type="hidden" id="'.$option['id'].'" name="'.$option['id'].'" value="'.$value.'" '.$attributes.' />';
			break;
			
			//textarea
			case 'textarea':
				$out.='<textarea id="'.$option['id'].'" name="'.$option['id'].'" '.$attributes.'>'.$value.'</textarea>';
			break;
			
			//custom dropdown
			case 'select':
				$out.='<select id="'.$option['id'].'" name="'.$option['id'].'" '.$attributes.'>';
				if(is_array($option['options'])) {
					foreach($option['options'] as $key=>$val) {
						$selected='';
						if($key==$value) {
							$selected='selected="selected"';
						}
						$out.='<option value="'.$key.'" '.$selected.'>'.$val.'</option>';
					}
				}
				$out.='</select>';
			break;
			
			//categories dropdown
			case 'select_category':
				$taxonomy='category';
				if(isset($option['taxonomy'])) {
					$taxonomy=$option['taxonomy'];
				}	
				$args=array(
					'hide_empty'         => 0,
					'show_option_all'    => __('All Categories','midway'),
					'echo'               => 0,
					'selected'           => $value,
					'hierarchical'       => 0, 
					'name'               => $option['id'],
					'id'				 => $option['id'],
					'class'              => 'postform',
					'depth'              => 0,
					'tab_index'          => 0,
					'taxonomy'           => $taxonomy,
					'hide_if_empty'      => false
				);	
				$out.= wp_dropdown_categories($args);
			break;

			//pages dropdown
			case 'select_page':
				$args=array(
					'selected'         => $value,
					'echo'             => 0,
					'name'             => $option['id']
				);	
				$out.=wp_dropdown_pages($args);
			break;
			
			//checkbox
			case 'checkbox':			
				$checked='';
				if($value=='true') {
					$checked='checked="checked"';
				}
				$out.='<input type="checkbox" id="'.$option['id'].'" name="'.$option['id'].'" value="true" '.$checked.' '.$attributes.' />';
				if(isset($option['name'])) {
					$out.='<label for="'.$option['id'].'">'.$option['name'].'</label>';
				}				
			break;
			
			//colorpicker
			case 'color':
				$out.='<div id="'.$option['id'].'_picker" class="colorSelector themex_color"><div></div></div>';
				$out.='<input name="'.$option['id'].'" id="'.$option['id'].'" type="text" value="'.$value.'" '.$attributes.' />';
			break;
			
			//uploader
			case 'uploader':
				$out.='<input name="'.$option['id'].'" id="'.$option['id'].'" type="text" value="'.$value.'" '.$attributes.' />';
				$out.='<div class="themex_button upload_button">'.__('Browse','midway').'</div>';
			break;
			
			//image selector
			case 'select_image':
				if(is_array($option['options'])) {
					foreach($option['options'] as $key=>$image_url) {
						$out.='<image src="'.$image_url.'" alt="'.$key.'" />';
					}
				}
				$out.='<input name="'.$option['id'].'" id="'.$option['id'].'" type="hidden" value="'.$value.'" '.$attributes.' />';
			break;
			
			//post selector
			case 'select_post':				
				$query=new WP_Query( array('showposts'=>-1, 'post_type' => $option['post_type'], 'orderby' => 'title', 'order' => 'ASC') );				
				parse_str($value,$value_arr);
				$temp_post=$post;
				
				$multiple='';
				if(isset($option['attributes']['multiple'])) {
					$multiple='[]';
				}		

				$out.='<select id="'.$option['id'].'" name="'.$option['id'].$multiple.'" '.$attributes.'>';

				if(isset($option['default_option'])) {
					$out.='<option value="default">'.$option['default_option'].'</option>';
				}
				
				if($query->have_posts()) {
					while ($query->have_posts()) {
						$query->the_post();
						$selected='';
						if(in_array((string)$post->ID, $value_arr) || $post->ID==$value) {
							$selected='selected="selected"';
						}
						$out.='<option value="'.$post->ID.'" '.$selected.'>'.$post->post_title.'</option>';
					}
				}									
				$out.='</select>';
				$post=$temp_post;
			break;
			
			//slider
			case 'slider':
				$out.='<div class="themex_slider"></div><div class="slider_value"></div>';
				$out.='<div class="max_value hidden">'.$option['attributes']['max_value'].'</div>';
				$out.='<div class="min_value hidden">'.$option['attributes']['min_value'].'</div>';
				$out.='<div class="unit hidden">'.$option['attributes']['unit'].'</div>';
				$out.='<input name="'.$option['id'].'" id="'.$option['id'].'" type="hidden" value="'.$value.'" />';
			break;
			
			//gallery
			case 'gallery':				
				parse_str(html_entity_decode(urldecode($value)),$value_arr);
			
				$out.='<a class="repeatable-add button" style="float:left;" href="#">'.__('Add Field','midway').'</a>';								
				if ($value) {
					$i = 0;	
					foreach($value_arr as $row) {						
						$out.='<tr class="repeatable-field '.$option['id'].'" style="border-top:1px solid #eeeeee;"><th style="width:25%"></th><td><input placeholder="'.__('URL','midway').'" type="text" name="'.$option['id'].'['.$i.']" id="'.$option['id'].'['.$i.']" class="'.$option['class'].'" value="'.$row.'" style="width:70%; margin-right: 20px; float:left;" /><a style="float: left;" href="#" class="button image-button repeatable-upload">'.__('Browse','midway').'</a><a style="float:left;margin-left:10px;" class="repeatable-remove button" href="#">'.__('Remove','midway').'</a></td></tr>';
						$i++;
					}
				} else {
						$out.='<tr class="repeatable-field '.$option['id'].'" style="border-top:1px solid #eeeeee;"><th style="width:25%"></th><td><input placeholder="'.__('URL','midway').'" type="text" name="'.$option['id'].'[0]" id="'.$option['id'].'[0]" class="'.$option['class'].'" value="" style="width:70%; margin-right: 20px; float:left;" /><a style="float: left;" href="#" class="button image-button repeatable-upload">'.__('Browse','midway').'</a><a style="float:left;margin-left:10px;" class="repeatable-remove button" href="#">'.__('Remove','midway').'</a></td></tr>';
				}
			break;
			
			//days
			case 'days':				
				parse_str(html_entity_decode(urldecode($value)),$value_arr);
			
				$out.='<a class="repeatable-add button" style="float:left;" href="#">'.__('Add Field','midway').'</a>';								
				if ($value) {
					$i = 0;	
					foreach($value_arr as $row) {
						$out.='<tr class="repeatable-field '.$option['id'].'" style="border-top:1px solid #eeeeee;"><th style="width:25%"></th><td>';
						$out.=ThemexInterface::renderOption(array(
						'type'=>'select',
						'id'=>$option['id'].'['.$i.']',
						'before'=>'<div style="width:40%;float:left;margin-right:40px;">',
						'after'=>'</div>',
						'default'=>$row,
						'options'=>array(
							'date'=>__('Departure Date','midway'),							
							'1'=>__('Monday','midway'),
							'2'=>__('Tuesday','midway'),
							'3'=>__('Wednesday','midway'),
							'4'=>__('Thursday','midway'),
							'5'=>__('Friday','midway'),
							'6'=>__('Saturday','midway'),
							'7'=>__('Sunday','midway'),
						),
						'attributes'=>array(
							'name'=>$option['id'].'['.$i.']',
						),
					));
						$out.='<a style="float:left;margin-left:10px;" class="repeatable-remove button" href="#">'.__('Remove','midway').'</a></td></tr>';
						$i++;
					}
				} else {
					$out.='<tr class="repeatable-field '.$option['id'].'" style="border-top:1px solid #eeeeee;"><th style="width:25%"></th><td>';
					$out.=ThemexInterface::renderOption(array(
						'type'=>'select',
						'id'=>$option['id'].'[0]',
						'before'=>'<div style="width:40%;float:left;margin-right:40px;">',
						'after'=>'</div>',
						'options'=>array(
							'date'=>__('Departure Date','midway'),							
							'monday'=>__('Monday','midway'),
							'tuesday'=>__('Tuesday','midway'),
							'wednesday'=>__('Wednesday','midway'),
							'thursday'=>__('Thursday','midway'),
							'friday'=>__('Friday','midway'),
							'saturday'=>__('Saturday','midway'),
							'sunday'=>__('Sunday','midway'),
						),
						'attributes'=>array(
							'name'=>$option['id'].'[0]',
						),
					));
					$out.='<a style="float:left;margin-left:10px;" class="repeatable-remove button" href="#">'.__('Remove','midway').'</a></td></tr>';
				}
			break;
			
			//links
			case 'links':		
				parse_str(html_entity_decode(urldecode($value)),$value_arr);

				$out.='<a class="repeatable-add button" style="float:left;" href="#">'.__('Add Field','midway').'</a>';								
				if ($value) {
					$i = 0;	
					foreach($value_arr as $row) {						
						$out.='<tr class="repeatable-field '.$option['id'].'" style="border-top:1px solid #eeeeee;"><th style="width:25%"></th><td><input placeholder="'.__('Label','midway').'" type="text" name="'.$option['id'].'['.$i.'][label]" id="'.$option['id'].'['.$i.'][label]" class="'.$option['class'].'" value="'.$row['label'].'" style="width:35%; margin-right: 20px; float:left;" /><input placeholder="'.__('URL','midway').'" type="text" name="'.$option['id'].'['.$i.'][url]" id="'.$option['id'].'['.$i.'][url]" class="'.$option['class'].'" value="'.$row['url'].'" size="30" style="width:40%; margin-right: 20px; float:left;" /><a style="float:left;" class="repeatable-remove button" href="#">'.__('Remove','midway').'</a></td></tr>';
						$i++;
					}
				} else {
					$out.='<tr class="repeatable-field '.$option['id'].'" style="border-top:1px solid #eeeeee;"><th style="width:25%"></th><td><input placeholder="'.__('Label','midway').'" type="text" name="'.$option['id'].'[0][label]" id="'.$option['id'].'[0][label]" class="'.$option['class'].'" value="" style="width:35%; margin-right: 20px; float:left;" /><input placeholder="'.__('URL','midway').'" type="text" name="'.$option['id'].'[0][url]" id="'.$option['id'].'[0][url]" class="'.$option['class'].'" value="" size="30" style="width:40%; margin-right: 20px; float:left;" /><a style="float:left;" class="repeatable-remove button" href="#">'.__('Remove','midway').'</a></td></tr>';
				}
			break;
			
			//Render module settings
			default:			
				if(isset(ThemexCore::$modules[$option['type']]) && method_exists(ThemexCore::$modules[$option['type']],'renderSettings')) {
					$out.=call_user_func(array(ThemexCore::$modules[$option['type']],'renderSettings'),$option['id']);	
				}
			break;
			
		}
		
		//add elements after
		if(isset($option['after'])) {
			$out=$out.$option['after'];
		}
		
		if($option['type']!='page') {
			$out.='<div class="clear"></div></div>';
		}		
		
		return $out;
	}	

}
?>